//当页面加载完成时 调用函数
var user = getCookie('username');
var listNum = 0;
$(() => {
    getName();
    reloading();
    sendAjax();
})
//将获取到的用户名放入右上角信息栏里
function getName() {
    if (user) {
        $('.userinfo a:first').text(user);
    }
}
//向后台发出ajax请求 拿取数据
function sendAjax() {
    let loadindex = layer.load(1, {
        shade: [0.4, "#000"]
    });
    $.get({
        url: './php/shopcart.php',
        data: {
            user: user,
            remove: 0,
            name: ''
        },
        success: res => {
            var { meta: { status, msg, data } } = JSON.parse(res);
            layer.close(loadindex);
            if (status === 1) {
                listNum = data.length;
                for (var i = 0; i < data.length; i++) {
                    let tr = $(`
                        <tr>
                            <th scope="row"><input type="checkbox"></th>
                            <td>
                                <img class="imgS" src="${data[i].src}" alt="">
                            </td>
                            <td>${data[i].name}</td>
                            <td class="unitPrice">${data[i].price}</td>
                            <td>
                                <form>
                                    <div class="btn1 cut">-</div>
                                    <input type="text" name="" id="" value="1">
                                    <div class="btn1 add">+</div>
                                </form>
                            </td>
                            <td class="subtotal">${data[i].price}</td>
                            <td>
                                <div class="btn2 remove">
                                    ×
                                </div>
                            </td>
                        </tr>
                    `)
                    $('tbody').append(tr);
                }
            } else {
                layer.msg(msg, {
                    icon: 2,
                    time: 1500
                })
            }
            $('.sum').text(listNum);
            btnClick();
            checkBox();
            btnRemove();
        }
    })
}
//给按钮绑定点击事件
function btnClick() {
    //增加减少商品的按钮
    $('.cut').click(function () {
        //更改输入框的值
        if (this.nextElementSibling.value <= 1)
            this.nextElementSibling.value = 1;
        else this.nextElementSibling.value--;
        //改变小计的值
        let p = Number(this.parentNode.parentNode.previousElementSibling.innerText.replace(/元*/g, ""));
        let s = Number(this.nextElementSibling.value) * p;
        this.parentNode.parentNode.nextElementSibling.innerText = `${s}元`;
        totalPrice()
    })
    //增加添加商品的按钮
    $('.add').click(function () {
        //更改输入框的值
        if (this.previousElementSibling.value >= 10)
            this.previousElementSibling.value = 10;
        else this.previousElementSibling.value++;
        let p = Number(this.parentNode.parentNode.previousElementSibling.innerText.replace(/元*/g, ""));
        let s = Number(this.previousElementSibling.value) * p;
        this.parentNode.parentNode.nextElementSibling.innerText = `${s}元`;
        totalPrice()
    })
}
//给复选框绑定点击事件
function checkBox() {
    //全选
    let i = 0;
    $('#allCheck').click(function () {
        if (this.checked) {
            $('input:checkbox').each(function () {
                this.checked = true;
                $('.selNum').text(listNum);
                i = listNum;
            });
        } else {
            $('input:checkbox').each(function () {
                this.checked = false;
                $('.selNum').text(0);
                i = 0;
            });
        }
        totalPrice();
        btnSubmit();
    })
    //复选框点击事件
    $('input:checkbox').each(function (index) {
        if (index == 0) return;
        this.onclick = () => {
            let n = $('.selNum').text() - 0;
            if (this.checked) {
                $('.selNum').text(n + 1);
                i++;
            } else {
                $('.selNum').text(n - 1);
                i--;
            }
            if (i < 0) i = 0;
            if (i == $('input:checkbox').length - 1) {
                $('#allCheck')[0].checked = true;
            } else {
                $('#allCheck')[0].checked = false;
            }
            totalPrice();
            btnSubmit()
        }
    })
}
//计算总价的函数
function totalPrice() {
    //获取每行的小计
    let sumPrice = 0;
    $('tbody tr').each(function () {
        if (this.children[0].firstElementChild.checked) {
            let price = Number(this.children[5].innerText.replace(/元*/g, ""));
            sumPrice += price;
        }
    })
    $('.sPriceNum').text(sumPrice);
}
//结算按钮的函数
function btnSubmit() {
    if (($('.selNum').text() - 0) > 0) {
        $('.btn3').css({
            background: 'rgb(242,88,7)',
            cursor: 'pointer',
            color: '#fff'
        });
    } else {
        $('.btn3').css({
            background: 'rgb(224, 224, 224)',
            cursor: 'default',
            color: 'rgb(117, 117, 117)'
        });
    }
}
//删除按钮的函数
function btnRemove() {
    //给删除按钮绑定事件
    $('.remove').each(function () {
        this.onclick = () => {
            let loadindex = layer.load(1, {
                shade: [0.4, "#000"]
            });
            //获取商品名字
            let goodsName = this.parentNode.parentNode.children[2].innerText;
            console.log(goodsName);
            // return;
            //发送ajax请求
            $.get({
                url: './php/shopcart.php',
                data: {
                    user: user,
                    remove: 1,
                    name: goodsName
                },
                success: res => {
                    console.log(res);
                    console.log(JSON.parse(res));
                    var { meta: { status, msg } } = JSON.parse(res);
                    layer.close(loadindex);
                    if (status === 1) {
                        //先删除tr节点
                        // this.parentNode.parentNode.remove();
                        layer.msg(msg, {
                            icon: 1,
                            time: 1500
                        })
                        location.reload();
                    } else {
                        layer.msg(msg, {
                            icon: 2,
                            time: 1500
                        })
                    }
                }
            })
        }
    })
}
//初始化函数
function reloading() {
    $('input:checkbox').each(function () {
        this.checked = false;
    });
}
